#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTreeWidget>
#include <QTreeWidgetItem>
#include <QStringList>
#include <QCoreApplication>
#include <QKeyEvent>
#include <QFile>
#include <QDebug>
#include <QTime>
#include <QLabel>
#include <QScrollBar>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_ptrStuSql(nullptr)
{
    ui->setupUi(this);

    // InitStyle();

    m_dlgLogin.show();
    connect(&m_dlgLogin, &Page_login::sendLoginSuccess, this, [=](){
        this->show();
    });

    ui->treeWidget->clear();
    ui->treeWidget->setColumnCount(1);

    QStringList l;
    l << "学生信息管理系统";

    QTreeWidgetItem *pf = new QTreeWidgetItem(ui->treeWidget, l);
    ui->treeWidget->addTopLevelItem(pf);

    l.clear();
    l << "学生管理";
    QTreeWidgetItem *p1 = new QTreeWidgetItem(pf, l);

    l.clear();
    l << "管理员管理";
    QTreeWidgetItem *p2 = new QTreeWidgetItem(pf, l);

    pf->addChild(p1);
    pf->addChild(p2);

    ui->treeWidget->expandAll();
    //ui->stackedWidget->setCurrentIndex(0); // 设置显示当前页，需要注释掉，不然没内容
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);


    //只选择行并且不可编辑
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    // ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);

    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);


    //设置水平、垂直滚动栏样式
    ui->tableWidget->horizontalScrollBar()->setStyleSheet("QScrollBar{background:transparent; height:10px;}"
    "QScrollBar::handle{background:lightgray; border:2px solid transparent; border-radius:5px;}"
    "QScrollBar::handle:hover{background:gray;}"
    "QScrollBar::sub-line{background:transparent;}"
    "QScrollBar::add-line{background:transparent;}");

    ui->tableWidget->verticalScrollBar()->setStyleSheet("QScrollBar{background:transparent; width: 10px;}"
    "QScrollBar::handle{background:lightgray; border:2px solid transparent; border-radius:5px;}"
    "QScrollBar::handle:hover{background:gray;}"
    "QScrollBar::sub-line{background:transparent;}"
    "QScrollBar::add-line{background:transparent;}");

    ui->tableWidget->horizontalHeader()->setHighlightSections(false); // 避免表格塌陷问题

    m_ptrStuSql = stuSql::getintance();
    m_ptrStuSql->init();

    UpdateTable();
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_btn_exit_clicked()
{
    exit(0);
}

void MainWindow::InitStyle()
{   
    QFile f;
    auto s = QCoreApplication::applicationDirPath();
    f.setFileName(s + "//" + "main.css");
    f.open(QIODevice::ReadOnly);

    QString str = f.readAll();
    this->setStyleSheet(str);
    m_dlgLogin.setStyleSheet(str);
}

#include <QRandomGenerator> // 需要包含此头文件

void MainWindow::on_btn_simulation_clicked()
{
    // Qt 6 使用 QRandomGenerator，无需手动设置种子

    // 准备姓名组件
    QStringList firstNames = {"赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈",
                              "褚", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "尤", "许"};
    QStringList lastNames = {"伟", "芳", "娜", "俊", "强", "磊", "敏", "静", "杰", "艳",
                             "超", "勇", "娟", "涛", "明", "霞", "秀英", "军", "丽", "平",
                             "刚", "鹏", "婷", "洋", "宇", "浩", "鑫", "欣", "睿", "琪"};

    // 电话号码前缀
    QStringList phonePrefix = {"130", "131", "132", "133", "135", "136", "137",
                               "138", "139", "150", "151", "155", "156", "157",
                               "158", "159", "185", "186", "187", "188", "189"};

    // 生成50条数据
    for(int i = 0; i < 50; i++){
        StuInfo info;

        // 生成姓名（姓氏+双字名）
        info.name = firstNames[QRandomGenerator::global()->bounded(firstNames.size())] +
                    lastNames[QRandomGenerator::global()->bounded(lastNames.size())] +
                    lastNames[QRandomGenerator::global()->bounded(lastNames.size())];

        // 年龄（7-14岁）
        info.age = QRandomGenerator::global()->bounded(8) + 7;

        // 年级（3-12年级）
        info.grade = QRandomGenerator::global()->bounded(10) + 3;

        // 班级（1-20班）
        info.uiclass = QRandomGenerator::global()->bounded(20) + 1;

        // 学号
        info.studentid = info.age * 10000 + info.grade * 100 + info.uiclass;

        // 生成电话号码（11位）
        info.phone = phonePrefix[QRandomGenerator::global()->bounded(phonePrefix.size())] +
                     QString("%1").arg(QRandomGenerator::global()->bounded(100000000), 8, 10, QChar('0'));

        // 生成微信ID（wxid_开头+8位随机字母数字组合）
        QString chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        QString randomPart;
        for(int j = 0; j < 8; ++j) {
            randomPart += chars[QRandomGenerator::global()->bounded(chars.length())];
        }
        info.wechat = "wxid_" + randomPart;

        m_ptrStuSql->addStu(info);
    }
    UpdateTable();
}


void MainWindow::on_lb_clear_clicked()
{
    m_ptrStuSql->cleaStuTable();
    UpdateTable();
}

void MainWindow::UpdateTable()
{
    ui->tableWidget->clear();
    // QTable 在设头行表之前需要先给头行设定一个列数，否则不会有数据，还有需要把控件的表头，不然也不会有数据
    ui->tableWidget->setColumnCount(8);

    QStringList l;
    l<<"序号 id"<<"姓名"<<"年龄"<<"年级"<<"班级"<<"学号"<<"电话"<<"微信";
    ui->tableWidget->setHorizontalHeaderLabels(l);

    auto cnt = m_ptrStuSql->getStuCnt();
    ui->lb_cnt->setText(QString("学生人数: %1").arg(cnt));

    QList<StuInfo> lStudents = m_ptrStuSql->getPageStu(0, cnt);

    ui->tableWidget->setRowCount(cnt);
    for(int i=0; i < lStudents.size(); i++)
    {
        ui->tableWidget->setItem(i, 0, new QTableWidgetItem(QString::number(lStudents[i].id)));
        ui->tableWidget->setItem(i, 1, new QTableWidgetItem(lStudents[i].name));
        ui->tableWidget->setItem(i, 2, new QTableWidgetItem(QString::number(lStudents[i].age)));
        ui->tableWidget->setItem(i, 3, new QTableWidgetItem(QString::number(lStudents[i].grade)));
        ui->tableWidget->setItem(i, 4, new QTableWidgetItem(QString::number(lStudents[i].uiclass)));
        ui->tableWidget->setItem(i, 5, new QTableWidgetItem(QString::number(lStudents[i].studentid)));
        ui->tableWidget->setItem(i, 6, new QTableWidgetItem(lStudents[i].phone));
        ui->tableWidget->setItem(i, 7, new QTableWidgetItem(lStudents[i].wechat));
    }

}

void MainWindow::on_btn_add_clicked()
{
//    m_dlgAddStu.show();
    m_dlgAddStu.SetTye(true);
    m_dlgAddStu.exec(); // 当前页面置顶，其他页面无法拖动(模态对话框)
    UpdateTable();
}

void MainWindow::on_btn_update_clicked()
{
    StuInfo info;
    int i = ui->tableWidget->currentRow();
    if(i >= 0)
    {
        info.id = ui->tableWidget->item(i, 0)->text().toUInt();
        info.name = ui->tableWidget->item(i, 1)->text();
        info.age = ui->tableWidget->item(i, 2)->text().toUInt();
        info.grade = ui->tableWidget->item(i, 3)->text().toUInt();
        info.uiclass = ui->tableWidget->item(i, 4)->text().toUInt();
        info.studentid = ui->tableWidget->item(i, 5)->text().toUInt();
        info.phone = ui->tableWidget->item(i, 6)->text();
        info.wechat = ui->tableWidget->item(i, 7)->text();

        m_dlgAddStu.SetTye(false, info);
        m_dlgAddStu.exec(); // 当前页面置顶，其他页面无法拖动(模态对话框)
        UpdateTable();
    }
}

void MainWindow::on_btn_del_clicked()
{
    int i = ui->tableWidget->currentRow();
    if(i >= 0)
    {
        int id = ui->tableWidget->item(i, 0)->text().toUInt();
        m_ptrStuSql->delStu(id);
        UpdateTable();
        QMessageBox::information(nullptr, "信息", "删除成功");
    }
}

void MainWindow::on_btn_search_clicked()
{
    QString strFilter = ui->le_search->text();
    if(strFilter.isEmpty()) {
        QMessageBox::information(nullptr, "警告", "搜索为空");
        UpdateTable();
        return ;
    }

    ui->tableWidget->clear();
    // QTable 在设头行表之前需要先给头行设定一个列数，否则不会有数据，还有需要把控件的表头，不然也不会有数据
    ui->tableWidget->setColumnCount(8);

    QStringList l;
    l<<"序号 id"<<"姓名"<<"年龄"<<"年级"<<"班级"<<"学号"<<"电话"<<"微信";
    ui->tableWidget->setHorizontalHeaderLabels(l);

    auto cnt = m_ptrStuSql->getStuCnt();
    ui->lb_cnt->setText(QString("学生人数: %1").arg(cnt));

    QList<StuInfo> lStudents = m_ptrStuSql->getPageStu(0, cnt);
    int ind = 0;

    for(int i=0; i < lStudents.size(); i++)
    {
        if(!lStudents[i].name.contains(strFilter)) continue;
        ui->tableWidget->setItem(ind, 0, new QTableWidgetItem(QString::number(lStudents[i].id)));
        ui->tableWidget->setItem(ind, 1, new QTableWidgetItem(lStudents[i].name));
        ui->tableWidget->setItem(ind, 2, new QTableWidgetItem(QString::number(lStudents[i].age)));
        ui->tableWidget->setItem(ind, 3, new QTableWidgetItem(QString::number(lStudents[i].grade)));
        ui->tableWidget->setItem(ind, 4, new QTableWidgetItem(QString::number(lStudents[i].uiclass)));
        ui->tableWidget->setItem(ind, 5, new QTableWidgetItem(QString::number(lStudents[i].studentid)));
        ui->tableWidget->setItem(ind, 6, new QTableWidgetItem(lStudents[i].phone));
        ui->tableWidget->setItem(ind, 7, new QTableWidgetItem(lStudents[i].wechat));
        ind++;
    }
    ui->tableWidget->setRowCount(ind);
}





























